const { chromium } = require('playwright');
// node-fetch from v3 is an ESM-only module - you are not able to import it with require().
// If you cannot switch to ESM, please use v2 which remains compatible with CommonJS. Critical bug fixes will continue to be published for v2.
const fetch = require('node-fetch');
const schedule = require('node-schedule');


const baseApi = "https://bgsmgi.eooiu.com/prod-api";
// const baseApi = "http://localhost:10030";


function parseQueryParams(text) {
  const queryReg = new RegExp(/.*\?(.*)/g)
  let regExpMatchArray1 = text.match(queryReg)
  console.log(regExpMatchArray1)
  const queryParams = {}
  for (let regExpMatchArray1Element of regExpMatchArray1) {
    let arr = regExpMatchArray1Element.replace(queryReg, "$1").split("&")
    for (let string of arr) {
      let strings = string.split("=")
      queryParams[strings[0]] = strings[1]
    }
  }
  // console.log(queryParams)
  return queryParams
}

(async () => {
  const browser = await chromium.launch();
  // Create pages, interact with UI elements, assert values
  const context = await browser.newContext();
  const page = await context.newPage();

  // Subscribe to 'request' and 'response' events.
  page.on('request', request => {
    if (request.url().indexOf('//express.baidu.com/express/api/express') !== -1) {
      const queryParams = parseQueryParams(request.url());
      console.log('>>', request.method(), request.url(), queryParams, request.headers())

      /**
       * parseQueryParams(request.url()) 打印结果如下
       * 
       * {
query_from_srcid: '4004',
isBaiduBoxApp: '10002',
isWisePc: '10020',
tokenV2: '7yY8CpEQ2HoyfNs5npEGQuS_G0jQkeGfIho98JtmjIUYiFzmk2JZv1AKt4Qhyxt6',
cb: 'jQuery110205931691906803072_1715414244867',
appid: '4001',
com: 'zhongtong',
nu: '73194968647599',
vcode: '',
token: '',
qid: 'd865419c0000181c',
_: '1715414244868'
}
参数 _ 代表时间戳
       */

      /**
       * request.headers() 打印结果如下
       * 
       * {
        'sec-ch-ua': '"HeadlessChrome";v="125", "Chromium";v="125", "Not.A/Brand";v="24"',
        referer: 'https://www.baidu.com/s?wd=%E4%B8%AD%E9%80%9A%E5%BF%AB%E9%80%92',
        'accept-language': 'en-US',
        'sec-ch-ua-mobile': '?0',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.6422.26 Safari/537.36',
        'sec-ch-ua-platform': '"Windows"'
      }
       */

      // 发送Token给目标程序
      const headers = request.headers()
      // request.headers().forEach(item => {
      //   headers[item.name] = item.value;
      // })
      fetch(`${baseApi}/baidu-express/update-token`, {
        headers: {
          "Content-Type": "application/json",
        },
        "body": JSON.stringify({
          ...queryParams,
          headers: headers,
        }),
        "method": "POST"
      }).then(function (res) {
        if (res.status === 200) {
          return res.json()
        } else {
          return Promise.reject(res.json())
        }
      }).then(function (data) {
        console.log(data);
      }).catch(function (err) {
        console.log(err);
      });

    }
  });
  page.on('response', response => {
    if (response.url().indexOf('//express.baidu.com/express/api/express') !== -1) {
      console.log('<<', response.status(), response.url())
    }
  });

  // 搜索关键词是中通快递和京东快递显示的界面是不一样的，这里使用搜索京东快递出现的界面。
  // await page.goto('https://www.baidu.com/s?wd=%E4%B8%AD%E9%80%9A%E5%BF%AB%E9%80%92');
  await page.goto('https://www.baidu.com/s?wd=京东快递');


  // 输入快递单号
  await page.fill('.op_express_delivery_input_nu', '73194968647599');
  await page.fill('.op_express_delivery_input_nu', '73194968647599');

  
const job = schedule.scheduleJob('0/10 * * * * ?', async function(){
  console.log('The answer to life, the universe, and everything!');
  // Use a glob URL pattern
  const [response] = await Promise.all([
    page.waitForResponse('**/api/express?**'),
    // 点击查询按钮
    page.click('.op_express_delivery_submit'),
  ]);
});

  // await browser.close();
})();